<?php

if (session::user() && session::user()->id == '1')
{

   if ($ajaxmode) // TODO: rewrite using API
   {
      # UPDATE LANGUAGE
      if (!empty($id) && !empty($_POST['alias']))
      {
         $sql  = 'UPDATE meccano_langs SET
            `alias` = "%s",
            `iso` = "%s",
            `domain` = "%s",
            `title` = "%s",
            `charset` = "%s",
            `dateformat` = "%s",
            `active` = "%i"
            WHERE `id` = %i';

         $values = array(
             (isset($_POST['alias']) ? $_POST['alias'] : NULL), 
             (isset($_POST['iso']) ? $_POST['iso'] : ''),
             (isset($_POST['domain']) ? $_POST['domain'] : ''),
             (isset($_POST['title']) ? $_POST['title'] : ''),
             (isset($_POST['charset']) ? $_POST['charset'] : 'UTF-8'),
             (isset($_POST['datef']) ? $_POST['datef'] : '%D'),
             (isset($_POST['active']) ? 1 : 0),
             $id);

         $DB->DB_QueryBuilder($sql, $values);
         if($DB->DB_Query())
         {
            echo json_encode(array('success'=>TRUE,'active'=>(isset($_POST['active']) ? TRUE : FALSE)));
            exit();
         }

         echo json_encode(array('success'=>FALSE));
         exit();
      }


      # CHANGE LANGUAGES SORTING
      if(!empty($_POST['position']))
      {
         $positions = array_filter($_POST['position'], 'is_numeric');
         if(!empty($positions))
         {
            $positions = array_values($positions);
            for($i=0, $t=sizeof($positions); $i<$t; $i++)
            {
               $DB->sql = 'UPDATE `meccano_langs` SET `position` = '. ($i+1) .' WHERE `id` = '. $positions[$i];
               $DB->DB_Query();
            }

            echo json_encode(array('success'=>TRUE));
            exit();
         }
         echo json_encode(array('success'=>FALSE));
         exit();
      }
   }

   $DB->sql = 'SELECT * FROM `meccano_langs` ORDER BY `position`';
   $DB->DB_Fetch();
   $SMARTY->assign('data', $DB->fetched);
   $layout = 'langs.html';
} else
{
   if (session::user())
   {
      $ErrorHandler->setError(
              array(
                  'code' => 'access',
                  'varkey' => 'access_denied'
              )
      );
   }
   $layout = 'login.html';
}